<?php
class Bricaboxadmin extends Controller {
	function Bricaboxadmin()
	{
		parent::Controller();
		
		// we should do some sanity checks here to ensure the current user is either:
		// 1. a superadmin
		// 2. the owner of this bricabox
		//
		// also, if no bricabox is available, just 404
		global $BBX;
		$this->load->model('Membership_model');
		if (!isset($BBX['bricabox'])
			|| !$this->userland->logged_in()
			|| ($this->userland->logged_in() && !$this->Membership_model->is_owner($BBX['bricabox']->id,
																					$this->userland->current_user()->id)
			   )
		)
		{
			if ($this->userland->logged_in())
				show_404();
			else
				echo "<html><body>Redirecting...<form id=\"loginform\" action=\"/sign_up_or_log_in\" method=\"post\"></form><script type=\"text/javascript\" charset=\"utf-8\">
				document.getElementById('loginform').submit();
			</script></body></html>";
			exit();
		}
	}
	
	function index()
	{
		//$this->output->cache(10); // 10 minute TTL
		
		global $BBX;
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: Manage your BricaBox",
			'first_content' => $this->db->query('select id from contents where bricabox_id = ? limit 1', array($BBX['bricabox']->id))->first_row()
		);
		$this->load->view('bricabox/admin/index', $data);
	}
	
	function general()
	{
		// just redirect to /basic
		header('Location: /admin/general/basic');
	}
	
	function members()
	{
		global $BBX;
		
		$this->load->model('Membership_model');
		$this->load->helper('string');
		
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: Manage members",
			'pending'	 => $this->Membership_model->get_pending($BBX['bricabox']->id),
			'members'	 => $this->Membership_model->get_members_of($BBX['bricabox']->id)
		);
		$this->load->view('bricabox/admin/members.php', $data);
	}
	
	function remove_application()
	{
		global $BBX;
		
		$login = $this->input->post('login');
		
		$this->db->query('delete from memberapplications
			where bricabox_id = ? and user_id =
				(select id from users where login = ? limit 1)',
			array($BBX['bricabox']->id, $login));
			
		$this->flashy->save_flash('notice', "Membership request removed.");
		header("Location: /admin/members");
	}
	
	function change_member_role()
	{
		$this->load->model('Membership_model');
		
		$role_id   = $this->input->post('change_role');
		$role_name = $this->Membership_model->get_role_for($role_id)->name;
		
		$login = $this->Membership_model->change_role_by_id(
			$this->input->post('bricabox_id'),
			$this->input->post('user_id'),
			$role_id
		);
		
		$this->flashy->save_flash('notice', "{$login}'s membership type has been changed to {$role_name}.");
		header('Location: /admin/members');
	}
	
	function add_member()
	{
		global $BBX;
		
		$this->load->model('Membership_model');
		
		$bricabox_id = $this->input->post("bricabox_id");
		
		// was a username or email passed in?
		$_v = $this->input->post("username_or_email");
		if (strpos($_v, '@') === false)
		{
			// username (user.login)
			if ($this->Membership_model->add_member($bricabox_id, $_v))
			{
				$this->flashy->save_flash('notice', "{$_v} is now a member of your BricaBox.");
				
				// send email
				$owner_email = $this->db->query('select email from users where login = ? limit 1', array($_v))->first_row()->email;
				$this->emailer->deliver_member_added(array(
					'to'		=> $owner_email,
					'subject'	=> "You're now a member of the {$BBX['bricabox']->name} BricaBox",
					'data'		=> array(
						'data' => array(
							'user' 		=> $_v,
							'url' 		=> bricabox_url($BBX['bricabox']),
							'bricabox'	=> $BBX['bricabox']->name
						)
					)
				));
			}
			else
				$this->flashy->save_flash('error', "{$_v} isn't a valid user or is already a member.");
		}
		else
		{
			// email address given; one of two things happens:
			//
			// 1. see if email belongs to existing user -> invite them
			// 2. no user, so create invitation and send to email addy
			
			$query = $this->db->query('select login from users where email = ? limit 1', array($_v));
			if ($query->num_rows() == 1)
			{
				// existing member
			}
			else
			{
				// send email and log to invite_codes
				$this->emailer->deliver_invite_member(array(
					'to'		=> $_v,
					'subject'	=> "You've been invited to the {$BBX['bricabox']->name} BricaBox",
					'data'		=> array(
						'data' => array(
							'user' 		=> $_v,
							'url' 		=> bricabox_url($BBX['bricabox']),
							'bricabox'	=> $BBX['bricabox']->name,
							'passcode'	=> $BBX['bricabox']->invite_code
						)
					)
				));
				
				// TODO
				//$this->db->query('insert into invite_codes')
				
				$this->flashy->save_flash('notice', "{$_v} has been sent an invitation to join this BricaBox.");
			}
		}
		header("Location: /admin/members");
	}
	
	function remove_member()
	{
		$this->load->model('Membership_model');
		
		$bricabox_id = $this->uri->segment(3);
		$user_id 	 = $this->uri->segment(4);
		
		$login = $this->Membership_model->remove_member($bricabox_id, $user_id);
		
		$this->flashy->save_flash('notice', "{$login} has been removed from your BricaBox.");
		header('Location: /admin/members');
	}
	
	function stats()
	{
		//$this->output->cache(10); // 10 minute TTL
		
		global $BBX;
		
		$p	= array($BBX['bricabox']->id);
		$mq = $this->db->query('select count(*) as count_all from memberships where bricabox_id = ?', $p);
		$eq = $this->db->query('select count(*) as count_all from contents where bricabox_id = ?', $p);
		
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: Stats",
			'entry_count' => $eq->first_row()->count_all,
			'member_count' => $mq->first_row()->count_all,
		);
		$this->load->view('bricabox/admin/stats', $data);
	}
	
	// admin/general/basic
	function gen_basic()
	{
		global $BBX;
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: General settings &rsaquo; Basic settings"
		);
		$this->load->view('bricabox/admin/general/basic', $data);
	}
	
	// admin/general/appearance
	function gen_appearance()
	{
		global $BBX;
		
		$this->load->model('Theme_model');
		
		$themes	= $this->Theme_model->load_all();
		
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: General settings &rsaquo; Site appearance",
			'themes'	 => $themes
		);
		$this->load->view('bricabox/admin/general/appearance', $data);
	}
	
	function gen_terms()
	{
		global $BBX;
		
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: General settings &rsaquo; Interaction"
		);
		$this->load->view('bricabox/admin/general/terms', $data);
	}
	
	function gen_domain()
	{
		global $BBX;
		
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: Custom domain settings"
		);
		$this->load->view('bricabox/admin/general/domain', $data);
	}
	
	function entry_templates()
	{
		global $BBX;
		
		$this->load->model('Bricabox_model');
		$this->load->model('Content_model');
		$this->load->helper('string');
		
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: Manage entry templates"
		);
		$this->load->view('bricabox/admin/entry_templates', $data);
	}
	
	function create_entry_template()
	{
		global $BBX;
		
		$this->load->model('Bricabox_model');
		if ($this->Bricabox_model->create_new_content_type($this->input->post("bricabox_id"), $this->input->post("tpl")))
		{
			$this->flashy->save_flash('notice', 'Your new entry template has been created!');
		}
		else
		{
			$name = $this->input->post('tpl');
			$name = $name['name'];
			$this->flashy->save_flash('error', 'An entry template named '.$name.' already exists.');
		}
		header('Location: /admin/entry_templates');
	}
	
	function save_entry_template()
	{
		global $BBX;
		
		$this->load->model('Bricabox_model');
		
		$name = $this->input->post('tpl');
		$name = $name['name'];
		
		if ($this->Bricabox_model->save_content_type($this->input->post("bricabox_id"), $this->input->post("tpl"), $this->input->post("current_name")))
		{
			$this->flashy->save_flash('notice', 'Your '.$name.' entry template has been saved!');
		}
		else
		{
			$this->flashy->save_flash('error', 'An entry template named '.$name.' already exists.');
		}
		header('Location: /admin/entry_templates');
	}
	
	function delete_entry_template()
	{
		$this->load->model('Content_model');
		
		$bricabox_id = $this->uri->segment(3);
		$type_id 	 = $this->uri->segment(4);
		
		if ($this->Content_model->content_type_can_be_deleted($type_id))
		{
			$this->Content_model->delete_content_type($type_id);
			$this->flashy->save_flash('notice', 'Entry template deleted.');
		}
		else
		{
			$this->flashy->save_flash('error', 'You can\'t delete that entry template.');
		}
		
		header('Location: /admin/entry_templates');
	}
	
	function entries()
	{
		header("Location: /entries");
	}
	
	function layout()
	{
		//$this->output->cache(10); // 10 minute TTL
		
		global $BBX;
		
		$this->load->model('Bricabox_model');
		
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: Edit site layout",
			'content'	 => $this->db->query('select id from contents where bricabox_id = ? limit 1', array($BBX['bricabox']->id))->first_row()
		);
		$this->load->view('bricabox/admin/layout', $data);
	}
	
	public function flagged_entries()
	{
		global $BBX;
		
		$this->load->model('Bricabox_model');
		$this->load->model('Content_model');
		$this->load->helper('string');
		
		$data = array(
			'BBX' 		 => $BBX,
			'bricabox' 	 => $BBX['bricabox'],
			'page_title' => "{$BBX['bricabox']->name}: Manage flagged entries"
		);
		$this->load->view('bricabox/admin/flagged', $data);
	}
	
	public function remove_flags()
	{
		$content_id = $this->uri->segment(3);
		$this->db->query("DELETE FROM content_flags WHERE content_id = ?", $content_id);
		header("Location: /admin/flagged_entries");
		exit;
	}
}
?>